<!-- 拖动放置容器 -->
<template>
  <div ref="dragDropRef" class="custom-drag-drop" :style="{ width: width, height: height }">
    <slot :data="data" :isDragover="isDragover"></slot>
  </div>
</template>

<script setup>
import { ref, onBeforeMount, onMounted, onBeforeUnmount, onUnmounted } from 'vue'
const props = defineProps({
  width: {
    type: [String, Number],
    default: 'unset'
  },
  height: {
    type: [String, Number],
    default: 'unset'
  }
})
const emit = defineEmits(['handleDrop'])
const dragDropRef = ref()
const data = ref()
const isDragover = ref(false)
onMounted(() => {
  initDrop()
})
onBeforeUnmount(() => {
  if (dragDropRef.value) {
    dragDropRef.value.removeEventListener('drop', handleDrop)
    dragDropRef.value.removeEventListener('dragleave', handleLeave)
    dragDropRef.value.removeEventListener('dragover', handleOver)
  }
})
function initDrop() {
  dragDropRef.value.addEventListener('drop', handleDrop)
  dragDropRef.value.addEventListener('dragleave', handleLeave)
  dragDropRef.value.addEventListener('dragover', handleOver)
}
function handleDrop(event) {
  data.value = JSON.parse(event.dataTransfer.getData('data'))
  // console.log('拖拽的数据:', data.value)
  emit('handleDrop', data.value)
  isDragover.value = false
}
function handleLeave(event) {
  isDragover.value = false
}
function handleOver(event) {
  //必须在dragover中阻止默认事件，否则drop事件不会生效
  event.preventDefault()
  isDragover.value = true
}
</script>
<style lang="scss" scoped></style>
